package com.cpointerz.jgtd.aspect;

import com.google.gson.Gson;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Aspect
@Component
public class ResponseAspect {
    @AllArgsConstructor
    private class Response{
        private int code;
        private String message;
        private Object data;
    }
    @Autowired
    private Gson gson;

    @Pointcut("@annotation(com.cpointerz.jgtd.aspect.annotation.JsonReturn)")
    public void pointcut(){}

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        try {
            Object result = pjp.proceed();
            Response resp = new Response(0, "Success", result);
            return gson.toJson(resp);
        } catch (Throwable t) {
            log.error("Caught Throwable: ", t);
            return gson.toJson(new Response(1, "Server error"+t.toString(), null));
        }
    }
}
